package vg.modules.connector;

import org.jgroups.Message;
import org.jgroups.ReceiverAdapter;
import vg.services.main_manager.VGMainServiceHelper;
import vg.services.plugin_manager.event_and_request.request.VGOpenGraphRequest;
import vg.services.plugin_manager.interfaces.IPlugin;
import vg_connector.implementation.ServerAPIService;
import vg_connector.interfaces.IServerAPIService;
import vg_connector.interfaces.IServerListener;
import vg_connector.interfaces.actions.OpenGraphAction;
import vg_connector.interfaces.actions.OpenGraphAnswer;
import vg_connector.interfaces.actions.ParentMessage;

import java.util.UUID;

/**
 * @author Timur Zolotuhin (e-mail: tzolotuhin@gmail.com)
 */
public class ConnectorPlugin implements IPlugin {
    // Main data
    private IServerAPIService serverAPIService;

    @Override
    public void install() throws Exception {
        UUID instanceId = VGMainServiceHelper.CmdLineOptions.appInstanceIdOption.getInstanceId();

        serverAPIService = new ServerAPIService();
        serverAPIService.connect(instanceId);

        serverAPIService.addServerListener(new IServerListener() {
            @Override
            public void connect() {

            }

            @Override
            public void disconnect() {

            }

            @Override
            public void receive(ParentMessage message) {
                if (message instanceof OpenGraphAction) {
                    doOpenGraphAction((OpenGraphAction)message);
                }
            }
        }
        );
    }

//==============================================================================
//------------------PRIVATE METHODS---------------------------------------------
    private void doOpenGraphAction(OpenGraphAction openGraphAction) {
        VGOpenGraphRequest vgOpenGraphRequest = new VGOpenGraphRequest(null);

        vgOpenGraphRequest.setName(openGraphAction.getName());
        vgOpenGraphRequest.setContent(openGraphAction.getContent());
        vgOpenGraphRequest.setFormat(openGraphAction.getFormat());

        VGMainServiceHelper.userInterfaceManager.sendRequest(vgOpenGraphRequest);

        // send answer
        OpenGraphAnswer openGraphAnswer = new OpenGraphAnswer();
        openGraphAnswer.setActionId(openGraphAction.getActionId());
        openGraphAnswer.setGraphId(-1);
        openGraphAnswer.setToId(openGraphAction.getFromId());

        try {
            VGMainServiceHelper.logger.printDebug("Sending answer for opening graph");

            serverAPIService.sendAnswer(openGraphAnswer);

            VGMainServiceHelper.logger.printDebug("Done");
        } catch (Exception ex) {
            VGMainServiceHelper.logger.printError("Sending answer error", ex);
        }
    }
}
